Skip to content

01 内置函数

写Python代码的时候,有些函数你几乎每一行都在用——print()len()range()list()……这些函数不需要import,打开Python解释器就能直接用,它们就是内置函数

内置函数是Python解释器自带的"工具箱",涵盖了类型转换、数据处理、迭代操作、对象检查等各种场景。你不需要记住所有内置函数,但常用的那十几个必须烂熟于心。

一、输出与输入

1.1 print()

最常用的函数,没有之一。把内容输出到控制台。

python
print("Hello Agent")
# 输出: Hello Agent

print("name:", "大志", "age:", 28)
# 输出: name: 大志 age: 28

print()有几个实用参数:

参数作用默认值
sep多个参数之间的分隔符' '
end输出结尾的字符'\n'
file输出目标sys.stdout
flush是否立即刷新False
python
# 自定义分隔符
print("2026", "06", "13", sep="-")
# 输出: 2026-06-13

# 不换行
print("loading", end="...")
# 输出: loading...(光标不会换行)

# 输出到文件
with open("log.txt", "w") as f:
    print("Agent启动成功", file=f)

1.2 input()

从控制台读取用户输入,返回字符串。

python
name = input("请输入你的名字: ")
print(f"你好, {name}!")

input()会阻塞程序,等用户输入完毕按回车才继续。注意返回值永远是字符串,需要数字得自己转换:

python
age = int(input("请输入年龄: "))

二、类型转换

Python是动态类型语言,类型转换函数用得非常多。

2.1 基本类型构造函数

python
# 转整数
int("42")        # 42
int(3.9)         # 3(截断,不是四舍五入)
int("0xff", 16)  # 255(十六进制转十进制)

# 转浮点数
float("3.14")    # 3.14
float(42)        # 42.0

# 转字符串
str(42)          # "42"
str(3.14)        # "3.14"
str(True)        # "True"
str(None)        # "None"

# 转布尔值
bool(0)          # False
bool("")         # False
bool([])         # False
bool(None)       # False
bool(1)          # True
bool("hello")    # True

记住bool()转换时,00.0""[]{}()None都是False,其他都是True

2.2 容器类型构造函数

python
# 转列表
list("abc")          # ['a', 'b', 'c']
list((1, 2, 3))      # [1, 2, 3]
list(range(5))       # [0, 1, 2, 3, 4]

# 转元组
tuple([1, 2, 3])     # (1, 2, 3)

# 转集合(自动去重)
set([1, 2, 2, 3, 3]) # {1, 2, 3}

# 转字典
dict([("name", "大志"), ("age", 28)])
# {'name': '大志', 'age': 28}

dict(name="大志", age=28)
# {'name': '大志', 'age': 28}

三、容器操作

3.1 len()

返回对象的长度。

python
len("hello")      # 5
len([1, 2, 3])    # 3
len({"a": 1})     # 1
len(range(10))    # 10

3.2 range()

生成整数序列,常用于for循环。

python
# range(stop):从0到stop-1
list(range(5))       # [0, 1, 2, 3, 4]

# range(start, stop):从start到stop-1
list(range(2, 6))    # [2, 3, 4, 5]

# range(start, stop, step):带步长
list(range(0, 10, 2))  # [0, 2, 4, 6, 8]
list(range(10, 0, -1)) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

range()不会一次性生成所有数字,而是按需生成,所以即使range(1000000)也不会占用太多内存。

3.3 sorted()

返回排序后的新列表,不修改原对象。

python
sorted([3, 1, 4, 1, 5])  # [1, 1, 3, 4, 5]

# 倒序
sorted([3, 1, 4], reverse=True)  # [4, 3, 1]

# 按key排序
students = [("大志", 85), ("小明", 92), ("小红", 78)]
sorted(students, key=lambda s: s[1])  # 按成绩排序
# [('小红', 78), ('大志', 85), ('小明', 92)]

# 字符串排序(按ASCII码)
sorted("hello")  # ['e', 'h', 'l', 'l', 'o']

3.4 enumerate()

遍历时同时获取索引和值。

python
fruits = ["苹果", "香蕉", "橘子"]

for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
# 0: 苹果
# 1: 香蕉
# 2: 橘子

# 指定起始索引
for i, fruit in enumerate(fruits, start=1):
    print(f"{i}: {fruit}")
# 1: 苹果
# 2: 香蕉
# 3: 橘子

3.5 zip()

并行遍历多个可迭代对象。

python
names = ["大志", "小明", "小红"]
scores = [85, 92, 78]

for name, score in zip(names, scores):
    print(f"{name}: {score}分")
# 大志: 85分
# 小明: 92分
# 小红: 78分

# 转成字典
dict(zip(names, scores))
# {'大志': 85, '小明': 92, '小红': 78}

# strict参数(3.10+),长度不一致时报错
list(zip([1, 2], [3, 4, 5], strict=True))
# ValueError: zip() has arguments with different lengths

3.6 reversed()

返回反向迭代器。

python
list(reversed([1, 2, 3]))  # [3, 2, 1]
list(reversed("hello"))    # ['o', 'l', 'l', 'e', 'h']

# 字符串反转
"".join(reversed("hello"))  # "olleh"

四、迭代器与生成器

4.1 map()

对可迭代对象的每个元素应用函数。

python
# 把字符串列表转成整数
list(map(int, ["1", "2", "3"]))  # [1, 2, 3]

# 每个元素平方
list(map(lambda x: x**2, [1, 2, 3]))  # [1, 4, 9]

# 多个可迭代对象
list(map(lambda x, y: x + y, [1, 2], [10, 20]))  # [11, 22]

4.2 filter()

过滤可迭代对象,保留使函数返回True的元素。

python
# 过滤偶数
list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5]))
# [2, 4]

# 过滤空字符串
list(filter(None, ["hello", "", "world", ""]))
# ['hello', 'world']

4.3 iter() 和 next()

手动操作迭代器。

python
# 创建迭代器
it = iter([1, 2, 3])

# 逐个获取元素
next(it)  # 1
next(it)  # 2
next(it)  # 3
next(it)  # StopIteration

# 设置默认值,避免StopIteration
next(it, "没有了")  # "没有了"

五、对象检查

5.1 type()

返回对象的类型。

python
type(42)          # <class 'int'>
type("hello")     # <class 'str'>
type([1, 2])      # <class 'list'>
type(None)        # <class 'NoneType'>

5.2 isinstance()

检查对象是否为指定类型的实例,支持继承关系。

python
isinstance(42, int)          # True
isinstance("hello", str)     # True
isinstance(42, (int, float)) # True(检查多个类型)

# 支持继承
class Animal: pass
class Dog(Animal): pass

dog = Dog()
isinstance(dog, Dog)     # True
isinstance(dog, Animal)  # True(Dog继承自Animal)

建议用isinstance()而不是type()来检查类型,因为isinstance()支持继承。

5.3 callable()

检查对象是否可调用(函数、类、实现了__call__的对象)。

python
callable(print)      # True
callable(len)        # True
callable(int)        # True(类也是可调用的)
callable(42)         # False
callable("hello")    # False

5.4 hasattr() / getattr() / setattr()

动态操作对象属性。

python
class Agent:
    name = "大志"
    version = 1.0

agent = Agent()

# 检查属性是否存在
hasattr(agent, "name")     # True
hasattr(agent, "age")      # False

# 获取属性
getattr(agent, "name")     # "大志"
getattr(agent, "age", 0)   # 0(默认值)

# 设置属性
setattr(agent, "age", 28)
agent.age  # 28

六、聚合函数

6.1 min() / max() / sum()

python
min(1, 2, 3)        # 1
max(1, 2, 3)        # 3
sum([1, 2, 3])      # 6
sum([1, 2, 3], 10)  # 16(初始值为10)

# 带key参数
students = [("大志", 85), ("小明", 92), ("小红", 78)]
min(students, key=lambda s: s[1])  # ('小红', 78)
max(students, key=lambda s: s[1])  # ('小明', 92)

6.2 abs() / round()

python
abs(-42)      # 42
abs(3.14)     # 3.14

round(3.14)   # 3
round(3.5)    # 4
round(3.14159, 2)  # 3.14(保留2位小数)

七、其他常用函数

7.1 open()

打开文件,返回文件对象。详见文件IO章节。

python
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()

7.2 format()

格式化输出。

python
format(3.14159, ".2f")    # "3.14"
format(42, "05d")         # "00042"
format(0.85, ".1%")       # "85.0%"
format(255, "x")          # "ff"(十六进制)

7.3 id() / hash()

python
# id()返回对象的唯一标识(内存地址)
a = [1, 2, 3]
b = a
id(a) == id(b)  # True(同一个对象)

# hash()返回对象的哈希值(字典的key必须可哈希)
hash("hello")   # 某个整数
hash(42)        # 42
hash((1, 2))    # 可以哈希
hash([1, 2])    # TypeError: unhashable type: 'list'

7.4 vars() / dir()

python
# vars()返回对象的__dict__属性
class Agent:
    def __init__(self):
        self.name = "大志"
        self.version = 1.0

agent = Agent()
vars(agent)  # {'name': '大志', 'version': 1.0}

# dir()返回对象的所有属性和方法
dir(agent)   # 包含__init__、name、version等

7.5 breakpoint()

进入调试器(3.7+)。

python
def process_data(data):
    result = data * 2
    breakpoint()  # 程序会在这里暂停,进入调试器
    return result

八、总结

内置函数是Python的"瑞士军刀",常用的就这些:

分类函数
输出输入print(), input()
类型转换int(), float(), str(), bool(), list(), dict(), set(), tuple()
容器操作len(), range(), sorted(), enumerate(), zip(), reversed()
迭代器map(), filter(), iter(), next()
对象检查type(), isinstance(), callable(), hasattr(), getattr(), setattr()
聚合函数min(), max(), sum(), abs(), round()
其他open(), format(), id(), hash(), vars(), dir(), breakpoint()

这些函数你每天写代码都会用到,不用刻意去背,用多了自然就记住了。遇到不认识的函数,直接在终端里敲help(函数名)就能看文档。